package io.hei.modules.sys.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import io.hei.common.utils.R;
import io.hei.modules.kbms.entity.KbmsFileInfoEntity;
import io.hei.modules.kbms.service.KbmsFileInfoService;
import io.hei.modules.kbms.service.KbmsFileMainService;
import io.hei.modules.sys.entity.SysUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/sys/file")
public class FileController extends AbstractController {
    @Value("${files.pathPrefix}")
    private String pathPrefix;

    @Value("${files.urlPrefix}")
    private String urlPrefix;

    @Autowired
    private KbmsFileInfoService kbmsFileInfoService;

    @Autowired
    private KbmsFileMainService kbmsFileMainService;

    /*
    * 文件上传
    * */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public R fileUpload(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
        if (file.getSize() == 0) {
            return R.error();
        }

        final SysUserEntity user = getUser();
        KbmsFileInfoEntity kbmsFileInfo = new KbmsFileInfoEntity();
        kbmsFileInfo.setFileId(UUID.randomUUID().toString());
        kbmsFileInfo.setFileName(file.getOriginalFilename());
        kbmsFileInfo.setFileSize(file.getSize());
        kbmsFileInfo.setFileType(file.getContentType());
        kbmsFileInfo.setPath(pathPrefix + file.getOriginalFilename());
        kbmsFileInfo.setUploadTime(new Date());
        kbmsFileInfo.setUserId(user.getUserId());
        kbmsFileInfoService.insert(kbmsFileInfo);

        File newFile = new File(pathPrefix + file.getOriginalFilename());
        file.transferTo(newFile);
        return R.ok().put("value", kbmsFileInfo.getFileId());
    }

    /*
    * 富文本上传本地图片
    * */
    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
    public R imageUpload(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
        if (file.getSize() == 0) {
            return R.error();
        }

        final SysUserEntity user = getUser();
        KbmsFileInfoEntity kbmsFileInfo = new KbmsFileInfoEntity();
        kbmsFileInfo.setFileId(UUID.randomUUID().toString());
        kbmsFileInfo.setFileName(file.getOriginalFilename());
        kbmsFileInfo.setFileSize(file.getSize());
        kbmsFileInfo.setFileType(file.getContentType());
        kbmsFileInfo.setPath(pathPrefix + file.getOriginalFilename());
        kbmsFileInfo.setUploadTime(new Date());
        kbmsFileInfo.setUserId(user.getUserId());
        kbmsFileInfoService.insert(kbmsFileInfo);

        File newFile = new File(pathPrefix + file.getOriginalFilename());
        file.transferTo(newFile);

        // 富文本上传本地文件回显
        return R.ok().put("value", urlPrefix + kbmsFileInfo.getFileName());
    }

    /*
    * 文件下载
    * */
    @RequestMapping(value = "/download/{origin_name}/{id}")
    public void download(HttpServletResponse response,
                         @PathVariable("origin_name") String origin_name,
                         @PathVariable("id") Long id) throws IOException {

        // 创建输出流对象
        ServletOutputStream outputStream = response.getOutputStream();

        //以字节数组的形式读取文件
        byte[] bytes = FileUtil.readBytes(pathPrefix + origin_name);

        // 设置返回内容格式
        response.setContentType("application/octet-stream");

        // 把文件名按UTF-8取出并按ISO8859-1编码，保证文件名中文不乱码
        // 设置文件名和格式（文件名要包括名字和文件格式）
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(origin_name.getBytes("UTF-8"),"ISO8859-1"));

        // 返回数据到输出流对象中
        outputStream.write(bytes);

        // 关闭流对象
        IoUtil.close(outputStream);

        // 文档下载数增加
        kbmsFileMainService.addDownloadNumByPrimaryKey(id);
    }

}

